package com.cy.uv.filter;

import com.auth0.jwt.interfaces.Claim;
import com.cy.uv.config.AuthProperties;
import com.cy.uv.util.Jwt;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class MyAuthGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //模拟校验过程，代码后面再来补完
        //获取请求头
        ServerHttpRequest request = exchange.getRequest();
        //判断是否是可以放行的路径
        if(isExclude(request)){
            return chain.filter(exchange);
        }

        //需要校验权限的路径
        List<String> authorization = request.getHeaders().get("authorization");
        String token= null;

        //获取token
        if(authorization!=null && !authorization.isEmpty()){
            token=authorization.get(0);
        }

        String username=null;

        try{
            Map<String, Claim> claims = Jwt.getClaims(token);
            if(claims.containsKey("username")){
                Claim claim = claims.get("username");
                username = claim.asString();
            }
            System.out.println(username);
        }catch (Exception e){
            System.out.println(e);//输出异常信息
            //如果出错，说明用户没有权限
            ServerHttpResponse response = exchange.getResponse();//取出响应对象
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//设置401，用户无权限标志位
            return response.setComplete();              //返回异步调用，后续拦截器不会再执行
        }

        return chain.filter(exchange);//成功，传递用户信息
    }
    private boolean isExclude(ServerHttpRequest request) {
        String url=request.getPath().toString();
        for(String excludeUrl:authProperties.getExecludePaths()){
            if(antPathMatcher.match(excludeUrl,url)){
                System.out.println("true");
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }

}

